package com.petRescueCenter.demo.user.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.petRescueCenter.demo.user.dao.UserDao;
import com.petRescueCenter.demo.user.entity.User;
import com.petRescueCenter.demo.user.entity.dto.UserDTO;

@Service
@Transactional
public class UserService implements IUserService {
	@Autowired
	private UserDao userDao;

	@Override
	public User save(User entity) {
		// TODO Auto-generated method stub
		return userDao.save(entity);
	}

	public User findById(Long id) {
		// TODO Auto-generated method stub
		return userDao.findById(id).get();
	}

	@Override
	public boolean existsById(Long id) {
		// TODO Auto-generated method stub
		return userDao.existsById(id);
	}

	@Override
	public long count() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void deleteById(Long id) {
		// TODO Auto-generated method stub
		userDao.deleteById(id);
	}

	@Override
	public void deleteAll(Long[] ids) {
		// TODO Auto-generated method stub

	}

	@Override
	@Transactional(readOnly = true)
	public Page<UserDTO> findAll(Specification<User> spec, Pageable pageable) {
		// TODO Auto-generated method stub
		Page<User> entityLists = userDao.findAll(spec, pageable);
		List<UserDTO> dtoLists = null;
		if (entityLists != null) {
			dtoLists = new ArrayList<UserDTO>();
			for (User entity : entityLists) {
				UserDTO dto = new UserDTO();
				UserDTO.entityToDto(entity, dto);

				dto.setAdoptTimes(userDao.getAdoptTimes(dto.getId()));
				dto.setAttentionTimes(userDao.getAttentionTimes(dto.getId()));
				dto.setPostTimes(userDao.getPostTimes(dto.getId()));
				// dto.setVoluntaryTimes(userDao.getVoluntaryTimes(dto.getId()));
				dtoLists.add(dto);
			}
		}
		return new PageImpl<UserDTO>(dtoLists, pageable, entityLists.getTotalElements());

	}

	@Override
	public boolean existsByName(String name) {
		// TODO Auto-generated method stub
		if (userDao.findByName(name) != null) {
			return true;
		}
		return false;
	}

	@Override
	public User findByName(String name) {
		// TODO Auto-generated method stub
		return userDao.findByName(name);
	}

}
